<?php
namespace App\Process;

use App\Job\CheckJob;
use App\Job\IotEvent;
use App\Model\Device;
use App\Model\Normal;
use Hyperf\AsyncQueue\Driver\DriverFactory;
use Hyperf\Config\Annotation\Value;
use Hyperf\Context\ApplicationContext;
use Hyperf\Process\AbstractProcess;
use Hyperf\Process\Annotation\Process;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Logger\LoggerFactory;
#[Process(name:'mqtt-subsribe')]
class MqttSubscribeProcess extends AbstractProcess{

    #[Value('mqtt-client.server')]
    private string $server;

    #[Value('mqtt-client.port')]
    private int $port;

    #[Value('mqtt-client.username')]
    private ?string $username;

    #[Value('mqtt-client.password')]
    private ?string $password;

    #[Value('mqtt-client.topic')]
    private string $topic;


    public function handle(): void
    {
        try{
            $connectSettings = (new \PhpMqtt\Client\ConnectionSettings())
                ->setUsername($this->username)
                ->setPassword($this->password);
            $mqtt = new \PhpMqtt\Client\MqttClient($this->server, $this->port);
            $mqtt->connect($connectSettings,true);
            $mqtt->subscribe($this->topic, function ($topic, $message) use($mqtt) {
                $strLen = strlen($message);
                $messageResult = [];
                $messageResultLog = [];
                for ($i = 0; $i < $strLen; $i ++) {
                    $item = ord(substr($message, $i, 1));
                    $messageResult[] = $item;
                    //转为16进制记录日志 方便使用
                    $messageResultLog[] = dechex($item);
                }
                preg_match('/(device\/)(.*)(?)(\/rx)/', $topic, $result);
                $imei = $result[2];
                $driver = ApplicationContext::getContainer()->get(DriverFactory::class)->get('iot-event');
                $driver->push(new IotEvent($imei,$messageResult));
//                 $device = Device::where('iot_sn', $imei)->first();
//                 if(!$device){
//                     $log_name = 'device' . date('Y-m-d', time());
//                     $loggerFactory = container()->get(\Hyperf\Logger\LoggerFactory::class);
//                     $logger = $loggerFactory->get($log_name, 'device');
//                     $logger->error('device['.$imei.'] not found -----'.date('Y/m/d H:i:s',time()));
//                 }
//
//                 $device->iotEventHandle($messageResult,$mqtt);
            }, 2);
            $mqtt->loop(true);
            $mqtt->disconnect();
        }catch (\Exception $e){
            Normal::logger('监听异常'.$e->getMessage(),'iotevent','error');
        }

    }
}
